package com.dly.blog.handle;

import com.dly.blog.msg.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Serializable;

/**
 * 认证异常处理
 */
@Component
@AllArgsConstructor
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable
{

    private final ObjectMapper objectMapper;

    private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException
    {
        int code = HttpServletResponse.SC_UNAUTHORIZED;
        String msg = "请求访问："+request.getRequestURI()+" 认证失败，无法访问系统资源";
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(objectMapper.writeValueAsString(R.error(code, msg)));
    }
}